package com.wbao.dianniu.ui;

import java.util.ArrayList;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.KeyEvent;
import android.view.MotionEvent;

import com.alibaba.mobileim.YWIMKit;
import com.alibaba.mobileim.conversation.IYWConversationService;
import com.alibaba.mobileim.conversation.IYWConversationUnreadChangeListener;
import com.lhh.apst.library.AdvancedPagerSlidingTabStrip;
import com.umeng.analytics.MobclickAgent;
import com.wbao.dianniu.R;
import com.wbao.dianniu.im.LoginSampleHelper;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.logical.SharedPreferencesUtils;
import com.wbao.dianniu.tabstrip.fragments.APSTSViewPager;
import com.wbao.dianniu.tabstrip.fragments.FirstFragment;
import com.wbao.dianniu.tabstrip.fragments.FourthFragment;
import com.wbao.dianniu.tabstrip.fragments.SecondFragment;
import com.wbao.dianniu.update.UpdateManager;
import com.wbao.dianniu.utils.Notification;
import com.wbao.dianniu.utils.Utils;

public class MainActivity extends FragmentActivity implements OnPageChangeListener {
	public static AdvancedPagerSlidingTabStrip mAPSTS;
    public APSTSViewPager mVP;

    private static final int VIEW_FIRST 		= 0;
    private static final int VIEW_SECOND	 = 1;
    private static final int VIEW_THIRD       = 2;
    private static final int VIEW_FOURTH    = 3;

    private static final int VIEW_SIZE = 4;

    private FirstFragment fistfragment;
    private SecondFragment secondFragment;
    private Fragment mThirdFragment = null;
    private FourthFragment fourthFragment;
    
    private long firstTime;
    private int showPage;
    private static Handler handler=null;
    private IYWConversationUnreadChangeListener mConversationUnreadChangeListener;
    private IYWConversationService mConversationService;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    	// TODO Auto-generated method stub
    	super.onCreate(savedInstanceState);
    	if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			Utils.setTranslucentStatus(this,true);
			SystemBarTintManager tintManager = new SystemBarTintManager(this);
			tintManager.setStatusBarTintEnabled(true);
			tintManager.setStatusBarTintResource(R.color.title_bg);// 通知栏所需颜色
		}
    	setContentView(R.layout.activity_main_inc);
    	Intent messageIntent = getIntent();
    	showPage = messageIntent.getIntExtra(GlobalContext.INTENT_IS_MESSAGE, VIEW_FIRST);
    	handler = new Handler();
        findViews();
        init();
        checkUpdate();
    }
    
	private void checkUpdate() {
		long time = SharedPreferencesUtils.getUpdateTime(this);
		if (System.currentTimeMillis() - time > 1000 * 60 * 60 * 24 ) {
			SharedPreferencesUtils.setUpdateTime(System.currentTimeMillis());
			UpdateManager update = new UpdateManager(this);
			update.checkUpdate();
		}
	}
    
    private void findViews(){
        mAPSTS = (AdvancedPagerSlidingTabStrip)findViewById(R.id.main_tabs);
        mVP = (APSTSViewPager)findViewById(R.id.main_apsts);
    }

    private void init(){
    	 mVP.setOffscreenPageLimit(VIEW_SIZE);
    	 //mVP.setScanScroll(false);
    	 mVP.setCurrentItem(showPage);
        FragmentAdapter adapter = new FragmentAdapter(getSupportFragmentManager());
        mVP.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        mAPSTS.setViewPager(mVP);
    	YWIMKit iMkit = LoginSampleHelper.getInstance().getIMKit();
    	mConversationService = iMkit.getConversationService();
		if(null != mConversationService){
			int counts = mConversationService.getAllUnreadCount();
			// 设置桌面角标的未读数
			iMkit.setShortcutBadger(counts);
			if(counts> 99){
				mAPSTS.showDot(VIEW_THIRD,"99+");
			}else if(counts > 0){
				mAPSTS.showDot(VIEW_THIRD, String.valueOf(counts));
			}
		}
		 initConversationServiceAndListener();
		mAPSTS.setOnPageChangeListener(this);
    }
    
	@Override
	public void onPageScrollStateChanged(int arg0) {
	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
	}

	@Override
	public void onPageSelected(int index) {
		if(VIEW_THIRD == index){
//			mAPSTS.hideDot(index);
		}
		
	}
    
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			long secondTime = System.currentTimeMillis();
			if (secondTime - firstTime > 800) {// 如果两次按键时间间隔大于800毫秒，则不退出
				Notification.toast(MainActivity.this, "再按一次退出程序");
				firstTime = secondTime;// 更新firstTime
				return true;
			} else {
//				LoginSampleHelper.getInstance().loginOut_Sample();
//				System.exit(0);// 否则退出程序 杀死进程
				this.finish();
			}
		}
    	return super.onKeyUp(keyCode, event);
    }

	private class FragmentAdapter extends FragmentStatePagerAdapter implements AdvancedPagerSlidingTabStrip.IconTabProvider{

        public FragmentAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            if(position >= 0 && position < VIEW_SIZE){
                switch (position){
                    case  VIEW_FIRST:
                    	if(null == fistfragment)
                    		fistfragment = FirstFragment.instance(MainActivity.this);
                    	return fistfragment;
                    case VIEW_SECOND:
                        if(null == secondFragment)
                        	secondFragment = SecondFragment.instance();
                        return secondFragment;
 
				case VIEW_THIRD:
					mThirdFragment = LoginSampleHelper.getInstance().getIMKit().getConversationFragment();
					return mThirdFragment;
                    case VIEW_FOURTH:
                        if(null == fourthFragment){
                        	fourthFragment = FourthFragment.instance();
                        }
                        return fourthFragment;
                    default:
                        break;
                }
            }
            return null;
        }

        @Override
        public int getCount() {
            return VIEW_SIZE;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            if(position >= 0 && position < VIEW_SIZE){
                switch (position){
                    case  VIEW_FIRST:
                        return  "电纽";
                    case  VIEW_SECOND:
                        return  "发现";
                    case  VIEW_THIRD:
                        return  "消息";
                    case  VIEW_FOURTH:
                        return  "我";
                    default:
                        break;
                }
            }
            return null;
        }

        @SuppressWarnings("unchecked")
		@Override
        public Integer getPageIcon(int index) {
            if(index >= 0 && index < VIEW_SIZE){
                switch (index){
                    case  VIEW_FIRST:
                        return  R.drawable.home_main_icon_one_n;
                    case VIEW_SECOND:
                        return  R.drawable.home_main_icon_two_n;
                    case VIEW_THIRD:
                        return  R.drawable.home_main_icon_third_n;
                    case VIEW_FOURTH:
                        return  R.drawable.home_main_icon_four_n;
                    default:
                        break;
                }
            }
            return 0;
        }

        @SuppressWarnings("unchecked")
		@Override
        public Integer getPageSelectIcon(int index) {
            if(index >= 0 && index < VIEW_SIZE){
                switch (index){
                    case  VIEW_FIRST:
                        return  R.drawable.home_main_icon_one_f;
                    case VIEW_SECOND:
                        return  R.drawable.home_main_icon_two_f;
                    case VIEW_THIRD:
                        return  R.drawable.home_main_icon_third_f;
                    case VIEW_FOURTH:
                        return  R.drawable.home_main_icon_four_f;
                    default:
                        break;
                }
            }
            return 0;
        }

        @Override
        public Rect getPageIconBounds(int position) {
            return null;
        }
    }
	
	/**
	 * 回调接口
	 * @author zhaoxin5
	 *
	 */
	public interface MyTouchListener
	{
	        public void onTouchEvent(MotionEvent event);
	}

	/*
	 * 保存MyTouchListener接口的列表
	 */
	private ArrayList<MyTouchListener> myTouchListeners = new ArrayList<MainActivity.MyTouchListener>();

	/**
	 * 提供给Fragment通过getActivity()方法来注册自己的触摸事件的方法
	 * @param listener
	 */
	public void registerMyTouchListener(MyTouchListener listener)
	{
	        myTouchListeners.add( listener );
	}

	/**
	 * 提供给Fragment通过getActivity()方法来取消注册自己的触摸事件的方法
	 * @param listener
	 */
	public void unRegisterMyTouchListener(MyTouchListener listener)
	{
	        myTouchListeners.remove( listener );
	}

	/**
	 * 分发触摸事件给所有注册了MyTouchListener的接口
	 */
	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		for (MyTouchListener listener : myTouchListeners) {
			listener.onTouchEvent(ev);
		}
		return super.dispatchTouchEvent(ev);
	}
	public void onResume() {
	    super.onResume();
	    MobclickAgent.onResume(this);       //统计时长
	}
	public void onPause() {
	    super.onPause();
	    MobclickAgent.onPause(this);
	}
	
	private void initConversationServiceAndListener(){
		mConversationUnreadChangeListener = new IYWConversationUnreadChangeListener() {
			
			@Override
			public void onUnreadChange() {
				// TODO Auto-generated method stub
				handler.post(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						LoginSampleHelper loginHelper = LoginSampleHelper.getInstance();
						final YWIMKit iMkit = loginHelper.getIMKit();
						mConversationService = iMkit.getConversationService();
						if (null != mConversationService) {
							int counts = mConversationService.getAllUnreadCount();
							// 设置桌面角标的未读数
							iMkit.setShortcutBadger(counts);
							if (counts > 99) {
								mAPSTS.showDot(VIEW_THIRD, "99+");
							} else if (counts > 0) {
								mAPSTS.showDot(VIEW_THIRD, String.valueOf(counts));
							}else{
								mAPSTS.hideDot(2);
							}
						}
					}
				});
			}
		};
		mConversationService.addTotalUnreadChangeListener(mConversationUnreadChangeListener);
	}
	
}
